package com.qf.ticketredis.controller;

import com.qf.ticketredis.pojo.R;
import com.qf.ticketredis.pojo.Ticket;
import com.qf.ticketredis.service.TicketService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.spring.boot.CuratorZkTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ticket")

@Api(tags = "卖票模块")
public class TicketController {

    @Autowired
    private TicketService ticketService;

	@Autowired
	private CuratorZkTemplate zkTemplate;

	private static final String LOCK_PREFIX = "/STU:LOCK:";

	@Value("${win}")
	private String win;

    @GetMapping("/sell/{id}")
	@ApiOperation("根据票务id卖票的接口")
	@ApiImplicitParam(name = "id",value = "票务信息的id")
    public R sell(@PathVariable("id") Integer id) throws Exception {

        while (true){

			//获取锁
			String lockName = LOCK_PREFIX+id;

			InterProcessLock lock = zkTemplate.getSharedReentrantLock(lockName);

			try {
				//加锁
				lock.acquire();
				//查询id对应的票务信息，是否有剩余票
				Ticket ticket = ticketService.getById(id);
				Integer count = ticket.getCount();
				if (count > 0) {
					System.out.println(win + "正在卖出第" + count + "张票");
					//模拟卖票时间
					Thread.sleep(1000);

					count = count - 1;

					//重新更新数据库的票务信息
					ticket.setCount(count);
					ticketService.updateById(ticket);
					System.out.println("剩余票数为：" + count);
				} else {
					break;
				}
			}finally {
				//释放锁
				lock.release();
			}
        }

		return R.success(new Ticket());
    }
}
